package com.norra.base.api

import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.IOException
import java.util.concurrent.TimeUnit

/**
 * Created by Charliu on 2019/02/18.
 */

class WebService private constructor() {

    companion object {
        private var token:String? = null
        private var api: Api? = null
            get() {
                if (field == null) {
                    field = createApi(Api.BASE_URL)
                }
                return field
            }


        fun get(): Api {
            return api!!
        }

        fun setToken(token:String?) {
            this.token = token
        }

        private fun createApi(baseUrl: String): Api {
            val retrofit = Retrofit.Builder()
                    .client(createHttpClient())
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(MyCallAdapterFactory())
                    .build()
            return retrofit.create(Api::class.java)
        }


        private fun createHttpClient(): OkHttpClient {
            return OkHttpClient.Builder()
                    .connectTimeout(20, TimeUnit.SECONDS)
                    .readTimeout(120, TimeUnit.SECONDS)
                    .addInterceptor(ParameterInterceptor())
                    .addInterceptor(LogInterceptor())
                    .build()
        }
    }


    private class ParameterInterceptor : Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            var request = chain.request()
            if (token != null) {
                request = request.newBuilder()
                        .header("Content-Type", "application/json")
                        .header("Authorization", token)
                        .build()
            }
            return chain.proceed(request)
        }
    }
}
